<template>
  <div class="update-value">
    <el-form inline>
      <el-form-item label="最新单价">
        <el-input v-model="latestPrice" @change="handleLatestPriceChange" />
      </el-form-item>
      <el-form-item label="最新市值">
        <el-input v-model="newHoldValue" @change="handleValueChange" />
      </el-form-item>
    </el-form>
    <div class="btn-area">
      <el-button @click="emit('close')">取消</el-button>
      <el-button type="primary" @click="confirmUpdateValue">确认</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { HoldItem } from '@/indexDB/initHold'
import { ref } from 'vue'
import { useHistory } from './useHistory'

const { handleHistory } = useHistory()
const props = defineProps<{
  form: HoldItem
  handleEditHoldItem: (form: HoldItem) => void
}>()

const emit = defineEmits(['close', 'confirm'])

const latestPrice = ref(+props.form.latestPrice)
const newHoldValue = ref(+props.form.holdValue)

const handleLatestPriceChange = () => {
  console.log('handleLatestPriceChange')
  newHoldValue.value = +(latestPrice.value * (props.form.holdNum ?? 1)).toFixed(4)
}

const handleValueChange = () => {
  // 持仓市值变了，计算单价
  latestPrice.value = +(newHoldValue.value / (props.form.holdNum ?? 1)).toFixed(4)
}

const confirmUpdateValue = () => {
  if (props.form) {
    const { holdNum, holdPrice } = props.form
    const holdValue = newHoldValue.value
    const totalCost = +(holdNum * holdPrice).toFixed(4)
    const newItem = {
      ...props.form,
      holdValue,
      latestPrice: +(holdValue / holdNum).toFixed(4),
      priceTime: new Date().getTime() + '',
      holdEarnings: +(holdValue - totalCost).toFixed(4),
      holdEarningsPercent: (((holdValue - totalCost) / totalCost) * 100).toFixed(2) + '%'
    }
    props.handleEditHoldItem(newItem)
    handleHistory(newItem)
    emit('confirm')
  }
}
</script>

<style lang="scss" scoped>
.btn-area {
  margin-top: 10px;
  text-align: end;
}
</style>
